<script setup lang="ts">
import AccFormItem from './components/acc-form-item.vue';
import SelectorGroup from './components/selector-group.vue';
import { useAccCommon } from './composables/use-acc-common';
import { DIRECT_REASON_LIST } from './constants/index';
import time from '@/utils/time';

const appStore = useAppStore();

const directStore = useDirectStore();

const formData = ref<{
  orderId: string | number;
  tranposId: string | number;
  tranposName: string;
  logistCenterId: string | number;
  logistCenterName: string;
  reasonId: string | number;
  reasonName: string;
  directrgMan: string;
  directPosName: string;
  checkDate: string;
  creDate: string;
  memo: string;
}>({
  orderId: '',
  tranposId: '',
  tranposName: '',
  logistCenterId: '',
  logistCenterName: '',
  reasonId: '',
  reasonName: '',
  directrgMan: '',
  directPosName: '',
  checkDate: '',
  creDate: '',
  memo: '',
});

// 使用优化后的 useAccCommon
const {
  tranposList,
  logistList,
  userList,
  reasonList,
  showStates,
  selectHandlers,
  closeHandlers,
  fetchTranposList,
  fetchLogistList,
  fetchUserList,
} = useAccCommon({
  onSelect: async (type: any, item: any) => {
    if (type === 'address') {
      formData.value.tranposId = item.id;
      formData.value.tranposName = item.name;
      formData.value.logistCenterId = '';
      formData.value.logistCenterName = '';
      formData.value.directrgMan = '';
      await fetchLogistList(item.id);
    } else if (type === 'logistics') {
      formData.value.logistCenterId = item.id;
      formData.value.logistCenterName = item.name;
      formData.value.directrgMan = '';
      if (formData.value.tranposId) {
        await fetchUserList(Number(formData.value.tranposId), item.id);
      }
    } else if (type === 'user') {
      formData.value.directrgMan = item.name;
    } else if (type === 'reason') {
      formData.value.reasonId = item.id;
      formData.value.reasonName = item.name;
    }
  },
});

const calendarRef = ref();

const handleClickLogist = () => {
  if (formData.value.tranposId) {
    showStates.logistics = true;
  } else {
    showToast('请先选择运输地址');
  }
};

const handleClickUser = () => {
  if (formData.value.logistCenterId) {
    showStates.user = true;
  } else {
    showToast('请先选择物流中心');
  }
};

const handleDateConfirm = (value: any) => {
  formData.value.checkDate = value.fulldate;
};

const handleSave = async () => {
  if (!formData.value.tranposId) {
    showToast('请选择运输地址');
    return;
  }
  if (!formData.value.logistCenterId) {
    showToast('请选择物流中心');
    return;
  }
  if (!formData.value.reasonId) {
    showToast('请选择直调原因');
    return;
  }
  if (!formData.value.directrgMan) {
    showToast('请选择直调人员');
    return;
  }
  if (!formData.value.directPosName) {
    showToast('请输入直调验收地点');
    return;
  }
  const params: any = {
    checkDate: formData.value.checkDate || time.format(new Date(), time.FORMATS.ISO_DATE),
    directPosName: formData.value.directPosName,
    directReason: formData.value.reasonId,
    directrgMan: formData.value.directrgMan,
    tranposId: formData.value.tranposId,
    logistCenterId: formData.value.logistCenterId,
    memo: formData.value.memo || '',
  };
  if (formData.value.orderId) {
    params.orderId = formData.value.orderId;
    await DirectService.modifyOrder(params);
  } else {
    params.customId = directStore.customerObj.customId;
    params.contactId = directStore.contactObj.contactId || '';
    params.entryId = directStore.customerObj.entryId;
    await DirectService.addOrder(params);
  }
  showSuccess('保存成功');
  appStore.setHadDoneOnDetail(true);
  directStore.setOrderDetailRefreshed(false);
  router.back();
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  // 判断是否为编辑模式（有 orderId 说明是编辑）
  const isEditMode = directStore.directDetailObj?.orderId;

  if (isEditMode) {
    // 编辑模式：从 store 获取数据
    formData.value = { ...directStore.directDetailObj };
    formData.value.reasonId = directStore.directDetailObj.directReason;
    formData.value.reasonName = findNameById(
      directStore.directDetailObj.directReason,
      DIRECT_REASON_LIST
    );

    // 加载级联数据
    if (formData.value.tranposId) {
      fetchLogistList(Number(formData.value.tranposId));
    }
    if (formData.value.logistCenterId) {
      fetchUserList(Number(formData.value.tranposId), Number(formData.value.logistCenterId));
    }
  } else {
    // 新增模式：重置表单数据
    formData.value = {
      orderId: '',
      tranposId: '',
      tranposName: '',
      logistCenterId: '',
      logistCenterName: '',
      reasonId: '',
      reasonName: '',
      directrgMan: '',
      directPosName: '',
      checkDate: '',
      creDate: '',
      memo: '',
    };
  }

  fetchTranposList();
});
</script>

<template>
  <view class="px-4 pt-10">
    <view class="text-17 flex font-bold">
      <view>总单</view>
      <view class="color-main-3">{{ formData.orderId ? '修改' : '新增' }}</view>
    </view>
    <view class="view-shadow mt-2">
      <up-form>
        <acc-form-item label="总单ID">
          <view class="w-full text-right color-gray-5">
            {{ formData.orderId || '-' }}
          </view>
        </acc-form-item>
        <acc-form-item label="运输地址" class="bg-white">
          <view
            :class="`w-full text-right ${formData.tranposId ? 'color-gray-5' : 'color-gray-6'}`"
            @click="showStates.address = true"
          >
            {{
              formData.tranposId
                ? `${formData.tranposId}/${formData.tranposName}`
                : '点击选择运输地址'
            }}
          </view>
        </acc-form-item>
        <acc-form-item label="物流中心" class="bg-white">
          <view
            :class="`w-full text-right ${formData.logistCenterId ? 'color-gray-5' : 'color-gray-6'}`"
            @click="handleClickLogist"
          >
            {{
              formData.logistCenterId
                ? `${formData.logistCenterId}/${formData.logistCenterName}`
                : '点击选择物流中心'
            }}
          </view>
        </acc-form-item>
        <acc-form-item label="直调原因" class="bg-white">
          <view
            :class="`w-full text-right ${formData.reasonName ? 'color-gray-5' : 'color-gray-6'}`"
            @click="showStates.reason = true"
          >
            {{ formData.reasonName || '点击选择直调原因' }}
          </view>
        </acc-form-item>
        <acc-form-item label="直调人员" class="bg-white">
          <view
            :class="`w-full text-right ${formData.directrgMan ? 'color-gray-5' : 'color-gray-6'}`"
            @click="handleClickUser"
          >
            {{ formData.directrgMan || '点击选择直调人员' }}
          </view>
        </acc-form-item>
        <acc-form-item label="直调验收地点" class="bg-white">
          <up-input
            v-model="formData.directPosName"
            placeholder="点击输入直调验收地点"
            inputAlign="right"
            fontSize="28rpx"
            border="none"
          />
        </acc-form-item>
        <acc-form-item label="直调验收时间" class="bg-white">
          <view
            :class="`w-full text-right ${formData.checkDate ? 'color-gray-5' : 'color-gray-6'}`"
            @click="calendarRef.open()"
          >
            {{
              formData.checkDate
                ? time.format(formData.checkDate, time.FORMATS.ISO_DATE)
                : '点击选择'
            }}
          </view>
        </acc-form-item>
        <acc-form-item v-if="formData.orderId" label="创建时间">
          <view :class="`w-full text-right ${formData.creDate ? 'color-gray-5' : 'color-gray-6'}`">
            {{ formData.creDate || '-' }}
          </view>
        </acc-form-item>
        <acc-form-item label="备注" class="bg-white" :borderBottom="false">
          <up-input
            v-model="formData.memo"
            placeholder="点击输入备注"
            :color="appStore.theme.color.text"
            inputAlign="right"
            fontSize="28rpx"
            border="none"
          />
        </acc-form-item>
      </up-form>
    </view>
    <app-calendar ref="calendarRef" @confirm="handleDateConfirm" />
    <selector-group
      :tranposList="tranposList"
      :logistList="logistList"
      :userList="userList"
      :reasonList="reasonList"
      :showStates="showStates"
      :selectHandlers="selectHandlers"
      :closeHandlers="closeHandlers"
    />
    <app-bottom-actions class="block mt-16" :count="2" :fixed="false">
      <app-action-btn class="flex-1" text="取消" @click="goBack" />
      <app-action-btn class="flex-1" text="保存" type="primary" @click="handleSave" />
    </app-bottom-actions>
  </view>
</template>
